package com.cx.thread;

import com.sun.org.apache.bcel.internal.generic.NEW;

import java.security.PublicKey;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author zhangshuai
 * @version V1.0
 * @Project Java2_26
 * @Package com.cx.thread
 * @Description:
 * @Date 2025/5/26 10:55
 */

public class ThreadTicketTest {

    public static void main(String[] args) {
        //线程安全问题解决 1.加锁 2.线程安全类或者接口
        //创建票对象  当前线程安全对象，只能保证不会多出票
        ConcurrentHashMap<String, Boolean> tickets = new ConcurrentHashMap<>();
        //添加票
        tickets.put("A",true);
        tickets.put("B",true);
        tickets.put("C",true);
        tickets.put("D",true);
        tickets.put("E",true);
        tickets.put("F",true);
        //创建火车对象
        Train train = new Train(tickets);

        //创建线程对象
       new MyTicketThread(train).start();
       new MyTicketThread(train).start();
       new MyTicketThread(train).start();
       new MyTicketThread(train).start();
       new MyTicketThread(train).start();
       new MyTicketThread(train).start();
       new MyTicketThread(train).start();
       new MyTicketThread(train).start();
       new MyTicketThread(train).start();
       new MyTicketThread(train).start();
       new MyTicketThread(train).start();
       new MyTicketThread(train).start();

       //
    }
}

//创建火车类
class Train{
    //票数
    private Map<String,Boolean> tickets;

    private Lock lock  = new ReentrantLock();

    public Train(Map<String, Boolean> tickets) {
        this.tickets = tickets;
    }
    //卖票的方法
    //同步方法 同步代码块 的区别   同步代码块只是去锁核心代码块，同步方法是锁整个方法，效率更高
    public  void saleTicket(){
        //加锁
//        lock.lock();
//        try {
            for (String ticket : tickets.keySet()) {
                //根据票的名字获取票的状态，如果票的状态为true，说明票可卖，否则false票已卖
                if(tickets.get(ticket)){
                    System.out.println(Thread.currentThread().getName() + "线程" + ticket + " 票已卖");
                    //票已卖，将票的状态改为false
                    tickets.put(ticket,false);
                    break; //跳出循环，避免重复卖票
                }
            }
//        }finally {
//            lock.unlock();//释放锁
//        }
        //同步代码块
//            synchronized (this){

//            }


    }



    //卖票的方法

}

//创建线程类
class  MyTicketThread extends Thread{
    private Train train;

    public MyTicketThread(Train train) {
        this.train = train;
    }



    @Override
    public void run() {
        //卖票
        train.saleTicket();
    }
}